<template>
  <div class="order-management">
    <h2>{{ t('admin.menu.orders') }}</h2>
    <p>{{ t('admin.orders.description') }}</p>
    
    <!-- Order management controls -->
    <el-card class="management-card">
      <template #header>
        <div class="card-header">
          <span>{{ t('admin.orders.orderList') }}</span>
          <el-button type="primary" @click="openOrderForm">
            {{ t('admin.orders.addOrder') }}
          </el-button>
        </div>
      </template>
      
      <!-- Search and filter -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input 
              v-model="filters.orderNumber" 
              :placeholder="t('admin.orders.orderNumber')"
              clearable
            />
          </el-col>
          <el-col :span="6">
            <el-select 
              v-model="filters.status" 
              :placeholder="t('admin.orders.status')"
              clearable
              style="width: 100%"
            >
              <el-option 
                v-for="status in statuses" 
                :key="status.value" 
                :label="t(`admin.orders.status.${status.value.toLowerCase()}`)"
                :value="status.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              :start-placeholder="t('admin.orders.startDate')"
              :end-placeholder="t('admin.orders.endDate')"
              style="width: 100%"
              clearable
            />
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="searchOrders">
              {{ t('common.search') }}
            </el-button>
            <el-button @click="resetFilters">
              {{ t('common.reset') }}
            </el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- Order table -->
      <el-table :data="orders" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" :label="t('admin.orders.id')" width="80"></el-table-column>
        <el-table-column prop="orderNumber" :label="t('admin.orders.orderNumber')"></el-table-column>
        <el-table-column prop="exchangeCodeId" :label="t('admin.orders.exchangeCodeId')"></el-table-column>
        <el-table-column prop="merchantId" :label="t('admin.orders.merchantId')"></el-table-column>
        <el-table-column prop="customerName" :label="t('admin.orders.customerName')"></el-table-column>
        <el-table-column prop="customerPhone" :label="t('admin.orders.customerPhone')"></el-table-column>
        <el-table-column prop="customerEmail" :label="t('admin.orders.customerEmail')"></el-table-column>
        <el-table-column :label="t('admin.orders.deliveryType')">
          <template #default="scope">
            <el-tag 
              :type="getDeliveryTypeType(scope.row.deliveryType)" 
              disable-transitions
            >
              {{ t(`admin.orders.deliveryType.${scope.row.deliveryType.toLowerCase()}`) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('admin.orders.status')">
          <template #default="scope">
            <el-tag 
              :type="getOrderStatusType(scope.row.status)" 
              disable-transitions
            >
              {{ t(`admin.orders.status.${scope.row.status.toLowerCase()}`) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" :label="t('admin.orders.createdAt')">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" :label="t('admin.orders.updatedAt')">
          <template #default="scope">
            {{ formatDate(scope.row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column :label="t('common.actions')" width="300">
          <template #default="scope">
            <el-button size="small" @click="viewOrder(scope.row)">
              {{ t('common.view') }}
            </el-button>
            <el-button size="small" @click="editOrder(scope.row)">
              {{ t('common.edit') }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteOrder(scope.row)">
              {{ t('common.delete') }}
            </el-button>
            <el-button size="small" type="warning" @click="cancelOrder(scope.row)" v-if="canCancelOrder(scope.row)">
              {{ t('admin.orders.cancel') }}
            </el-button>
            <el-button size="small" type="success" @click="shipOrder(scope.row)" v-if="canShipOrder(scope.row)">
              {{ t('admin.orders.ship') }}
            </el-button>
            <el-button size="small" type="primary" @click="deliverOrder(scope.row)" v-if="canDeliverOrder(scope.row)">
              {{ t('admin.orders.deliver') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Pagination -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- Order form dialog -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="800px"
      @close="resetOrderForm"
    >
      <el-form 
        :model="orderForm" 
        :rules="orderRules" 
        ref="orderFormRef" 
        label-width="150px"
      >
        <el-form-item :label="t('admin.orders.orderNumber')" prop="orderNumber">
          <el-input v-model="orderForm.orderNumber"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.orders.exchangeCodeId')" prop="exchangeCodeId">
          <el-input-number 
            v-model="orderForm.exchangeCodeId" 
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="t('admin.orders.merchantId')" prop="merchantId">
          <el-input-number 
            v-model="orderForm.merchantId" 
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="t('admin.orders.customerName')" prop="customerName">
          <el-input v-model="orderForm.customerName"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.orders.customerPhone')" prop="customerPhone">
          <el-input v-model="orderForm.customerPhone"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.orders.customerEmail')" prop="customerEmail">
          <el-input v-model="orderForm.customerEmail"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.orders.deliveryType')" prop="deliveryType">
          <el-select v-model="orderForm.deliveryType" style="width: 100%">
            <el-option 
              v-for="type in deliveryTypes" 
              :key="type.value" 
              :label="t(`admin.orders.deliveryType.${type.value.toLowerCase()}`)"
              :value="type.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
          v-if="orderForm.deliveryType === 'SHIP'" 
          :label="t('admin.orders.shippingAddress')" 
          prop="shippingAddress"
        >
          <el-input 
            v-model="orderForm.shippingAddress" 
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.orders.status')" prop="status">
          <el-select v-model="orderForm.status" style="width: 100%">
            <el-option 
              v-for="status in statuses" 
              :key="status.value" 
              :label="t(`admin.orders.status.${status.value.toLowerCase()}`)"
              :value="status.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
          <el-button type="primary" @click="saveOrder">{{ t('common.save') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'

export default {
  name: 'OrderManagement',
  setup() {
    const { t } = useI18n()
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const orderFormRef = ref(null)
    
    const orders = ref([])
    const selectedOrders = ref([])
    
    const filters = reactive({
      orderNumber: '',
      status: '',
      dateRange: []
    })
    
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    const orderForm = reactive({
      id: null,
      orderNumber: '',
      exchangeCodeId: null,
      merchantId: null,
      customerName: '',
      customerPhone: '',
      customerEmail: '',
      deliveryType: 'SHIP',
      shippingAddress: '',
      status: 'PENDING',
      createdAt: null,
      updatedAt: null,
      shippedAt: null,
      deliveredAt: null,
      cancelledAt: null
    })
    
    const deliveryTypes = ref([
      { value: 'SHIP', label: t('admin.orders.deliveryType.ship') },
      { value: 'PICKUP', label: t('admin.orders.deliveryType.pickup') }
    ])
    
    const statuses = ref([
      { value: 'PENDING', label: t('admin.orders.status.pending') },
      { value: 'CONFIRMED', label: t('admin.orders.status.confirmed') },
      { value: 'PROCESSING', label: t('admin.orders.status.processing') },
      { value: 'SHIPPED', label: t('admin.orders.status.shipped') },
      { value: 'DELIVERED', label: t('admin.orders.status.delivered') },
      { value: 'CANCELLED', label: t('admin.orders.status.cancelled') }
    ])
    
    const orderRules = {
      orderNumber: [
        { required: true, message: t('admin.orders.enterOrderNumber'), trigger: 'blur' }
      ],
      exchangeCodeId: [
        { required: true, message: t('admin.orders.enterExchangeCodeId'), trigger: 'blur' }
      ],
      merchantId: [
        { required: true, message: t('admin.orders.enterMerchantId'), trigger: 'blur' }
      ],
      customerName: [
        { required: true, message: t('admin.orders.enterCustomerName'), trigger: 'blur' }
      ],
      customerPhone: [
        { required: true, message: t('admin.orders.enterCustomerPhone'), trigger: 'blur' }
      ],
      customerEmail: [
        { required: true, message: t('admin.orders.enterCustomerEmail'), trigger: 'blur' },
        { type: 'email', message: t('admin.orders.invalidEmail'), trigger: 'blur' }
      ],
      deliveryType: [
        { required: true, message: t('admin.orders.selectDeliveryType'), trigger: 'blur' }
      ],
      shippingAddress: [
        { required: true, message: t('admin.orders.enterShippingAddress'), trigger: 'blur' }
      ],
      status: [
        { required: true, message: t('admin.orders.selectStatus'), trigger: 'blur' }
      ]
    }
    
    const getOrderStatusType = (status) => {
      const statusTypes = {
        PENDING: 'info',
        CONFIRMED: 'primary',
        PROCESSING: 'warning',
        SHIPPED: 'success',
        DELIVERED: 'success',
        CANCELLED: 'danger'
      }
      return statusTypes[status] || 'info'
    }
    
    const getDeliveryTypeType = (type) => {
      const typeTypes = {
        SHIP: 'primary',
        PICKUP: 'success'
      }
      return typeTypes[type] || 'info'
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString()
    }
    
    const canCancelOrder = (order) => {
      return ['PENDING', 'CONFIRMED', 'PROCESSING'].includes(order.status)
    }
    
    const canShipOrder = (order) => {
      return order.status === 'CONFIRMED' || order.status === 'PROCESSING'
    }
    
    const canDeliverOrder = (order) => {
      return order.status === 'SHIPPED'
    }
    
    const loadOrders = async () => {
      try {
        loading.value = true
        // In a real application, you would make an API call to fetch orders
        // For now, using mock data
        orders.value = [
          {
            id: 1,
            orderNumber: 'ORD20251028001',
            exchangeCodeId: 1,
            merchantId: 1,
            customerName: 'John Doe',
            customerPhone: '1234567890',
            customerEmail: 'john@example.com',
            deliveryType: 'SHIP',
            shippingAddress: '123 Main St, City, Country',
            status: 'PENDING',
            createdAt: '2025-10-28T10:00:00',
            updatedAt: '2025-10-28T10:00:00',
            shippedAt: null,
            deliveredAt: null,
            cancelledAt: null
          },
          {
            id: 2,
            orderNumber: 'ORD20251028002',
            exchangeCodeId: 2,
            merchantId: 1,
            customerName: 'Jane Smith',
            customerPhone: '0987654321',
            customerEmail: 'jane@example.com',
            deliveryType: 'PICKUP',
            shippingAddress: '',
            status: 'CONFIRMED',
            createdAt: '2025-10-28T11:00:00',
            updatedAt: '2025-10-28T11:30:00',
            shippedAt: null,
            deliveredAt: null,
            cancelledAt: null
          },
          {
            id: 3,
            orderNumber: 'ORD20251028003',
            exchangeCodeId: 3,
            merchantId: 2,
            customerName: 'Bob Johnson',
            customerPhone: '5551234567',
            customerEmail: 'bob@example.com',
            deliveryType: 'SHIP',
            shippingAddress: '456 Market St, City, Country',
            status: 'SHIPPED',
            createdAt: '2025-10-28T12:00:00',
            updatedAt: '2025-10-28T14:00:00',
            shippedAt: '2025-10-28T14:00:00',
            deliveredAt: null,
            cancelledAt: null
          }
        ]
        pagination.total = orders.value.length
      } catch (error) {
        console.error('Error loading orders:', error)
        ElMessage.error(t('admin.orders.errorLoadingOrders'))
      } finally {
        loading.value = false
      }
    }
    
    const searchOrders = () => {
      loadOrders()
    }
    
    const resetFilters = () => {
      filters.orderNumber = ''
      filters.status = ''
      filters.dateRange = []
      loadOrders()
    }
    
    const openOrderForm = () => {
      dialogTitle.value = t('admin.orders.addOrder')
      dialogVisible.value = true
    }
    
    const editOrder = (order) => {
      dialogTitle.value = t('admin.orders.editOrder')
      Object.assign(orderForm, order)
      dialogVisible.value = true
    }
    
    const viewOrder = (order) => {
      dialogTitle.value = t('admin.orders.viewOrder')
      Object.assign(orderForm, order)
      dialogVisible.value = true
    }
    
    const deleteOrder = (order) => {
      // In a real application, you would make an API call to delete the order
      console.log('Delete order:', order)
      ElMessage.success(t('admin.orders.orderDeleted'))
      loadOrders()
    }
    
    const cancelOrder = (order) => {
      // In a real application, you would make an API call to cancel the order
      order.status = 'CANCELLED'
      order.cancelledAt = new Date().toISOString()
      console.log('Cancel order:', order)
      ElMessage.success(t('admin.orders.orderCancelled'))
      loadOrders()
    }
    
    const shipOrder = (order) => {
      // In a real application, you would make an API call to ship the order
      order.status = 'SHIPPED'
      order.shippedAt = new Date().toISOString()
      console.log('Ship order:', order)
      ElMessage.success(t('admin.orders.orderShipped'))
      loadOrders()
    }
    
    const deliverOrder = (order) => {
      // In a real application, you would make an API call to deliver the order
      order.status = 'DELIVERED'
      order.deliveredAt = new Date().toISOString()
      console.log('Deliver order:', order)
      ElMessage.success(t('admin.orders.orderDelivered'))
      loadOrders()
    }
    
    const saveOrder = async () => {
      await orderFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // In a real application, you would make an API call to save the order
            console.log('Saving order:', orderForm)
            dialogVisible.value = false
            ElMessage.success(t('admin.orders.orderSaved'))
            loadOrders()
          } catch (error) {
            console.error('Error saving order:', error)
            ElMessage.error(t('admin.orders.errorSavingOrder'))
          }
        }
      })
    }
    
    const resetOrderForm = () => {
      Object.keys(orderForm).forEach(key => {
        if (key === 'deliveryType') {
          orderForm[key] = 'SHIP'
        } else if (key === 'status') {
          orderForm[key] = 'PENDING'
        } else if (key === 'exchangeCodeId' || key === 'merchantId') {
          orderForm[key] = null
        } else {
          orderForm[key] = ''
        }
      })
    }
    
    const handleSelectionChange = (selection) => {
      selectedOrders.value = selection
    }
    
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadOrders()
    }
    
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      loadOrders()
    }
    
    onMounted(() => {
      loadOrders()
    })
    
    return {
      t,
      loading,
      dialogVisible,
      dialogTitle,
      orderFormRef,
      orders,
      selectedOrders,
      filters,
      pagination,
      orderForm,
      deliveryTypes,
      statuses,
      orderRules,
      getOrderStatusType,
      getDeliveryTypeType,
      formatDate,
      canCancelOrder,
      canShipOrder,
      canDeliverOrder,
      loadOrders,
      searchOrders,
      resetFilters,
      openOrderForm,
      editOrder,
      viewOrder,
      deleteOrder,
      cancelOrder,
      shipOrder,
      deliverOrder,
      saveOrder,
      resetOrderForm,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.management-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>